<?php
/**
 * Conference Rooms
 *
 * @todo Forbid conflicting reservations
 * @todo Decent reserve form interface for dates and times
 */
include_once('init.php');

/*
* Main switch, handling the actions, which can be passed as PATH_INFO,
* as in http://whatever.com/conference.php/rooms or as a GET or POST
* variable called action.
*/
switch ( action() ) {

    case 'post' : // this is the generic POST handler
        post();
    break;

    case 'rooms' : // Show list of rooms
        show_rooms();
    break;

    case 'newroom' : // Form to add new rooms
        room_form( 'new' );
    break;

    case 'editroom' : // Form to edit room details
        $ID = false;
        if (isset($_GET['ID'])) {
            $ID = intval($_GET['ID']);
        } else {
            $args = explode( '/', $_SERVER['PATH_INFO'] );
            if (isset($args[2])) {
                $ID = intval($args[2]);
            }
        }
        $room = new room( array ( 'ID' => $ID ));
        room_form( 'edit', $room );
    break;

    case 'deleteroom' : // display confirmation page to delete a room
        delete_room();
    break;

    case 'event' : // Event details
        event_details();
    break;

    case 'reserve' : // Reserve a room
        reservation_form();
    break;

    case 'addreservation' : // Add the reservation
        add_reservation();
        show_schedule();
    break;

    case 'editreservation' : // Edit reservation values
        $args = explode( '/', $_SERVER{'PATH_INFO'} );
        $event = new event( array ( ID => $args[2] ) );
        reservation_form( $event );
    break;

    default : // Display the schedule
        show_schedule();
    break;

}

function show_header() {
}

function show_footer() {
    echo '<p><a href="' . CONFURI . MAINFILE . '">HOME</a></p>';
}

/**
 * Display the schedule of reserved rooms. Initially, we'll just show
 * all the rooms. Eventually, we'll want a way to filter by ...
 * something. Let's start simple.
 * 
 * @todo Filter by room
 * @todo next, previous day, week, etc
 * @tody Week, month view.
 */
function show_schedule() {

    show_header();

    // What's today?
    if ($_SERVER['PATH_INFO']) {
        $args = explode( '/', $_SERVER['PATH_INFO'] );
        if (strlen(intval($args[1])) == 8) {
            $day = new day( $args[1] );
        } else {
            $day = new day();
        }
    }

    if ( ! $day ) {
        $day = new day();
    }
    $events = event::allevents( $day->ymd() );

    echo '<a href="' . CONFURI . MAINFILE . '/rooms">Rooms</a>';
    echo '<h2>Events for ' .
          date('M d Y', $day->gmtime() ) . '</h2>' .
         '<table border="1"><tr><td></td>';
    // Now, the real hard work begins. This builds a data structure
    // $struct which contains all the events and their placement. Once
    // this is done, displaying it becomes simple.
    $struct = array();
    foreach ( $events as $event ) {

        // Mark the start time
        $struct[$event->roomID()][$event->starttime()] = $event->ID();
        $struct['events'][$event->ID()] = $event;

        // Block off everything up to the end time
        $time = $event->starttime();
        $length = 1;
        $time = timeadd( $time, SCHEDSLOT );
        while ( $time < $event->endtime() ) {
            $struct[$event->roomID()][$time] = 'x';
            $time = timeadd( $time, SCHEDSLOT );
            $length++;
        }
        $struct['lengths'][$event->ID()] = $length;
    }

    // First, show all the rooms
    $cols = 0;
    foreach ( room::allrooms() as $room ) {
        echo '<td><a href="' . CONFURI . MAINFILE . '/room/' .
            $room->ID() . '">' . $room->name() . '</a></td>';
        $cols++;
        $room_col[$cols] = $room->ID();
        $rooms[$room->ID()] = $room;
    }
    echo '</tr>';

    // Next, go through all the timeslots, and show the events, if any,
    // scheduled for that slot
    $time = DAYSTART;
    while ( $time < DAYEND ) {
        echo '<tr><td>' . $time . '</td>';

        // Loop through the rooms, and see if there's a scheduled event
        for ( $c = 1; $c <= $cols; $c++ ) {

            // If the time is blocked off, we're already in the middle
            // of a multi-row table cell.
            if ( $struct[$c][$time] == 'x' ) {
                // Do nothing

            // If an event starts here, make a table cell that spans the
            // whole length of the event.
            } elseif ( $struct[$c][$time] ) {
                echo '<td
                    onClick="location.href=\'' . CONFURI . MAINFILE .
                    '/event/' . $struct[$c][$time] . '\'"' .
                    'rowspan="' . 
                    $struct['lengths'][ $struct[$c][$time] ] . '">' .
                    $struct['events'][ $struct[$c][$time] ]->name() . 
                '</td>';

            // Vacant slots are linked to a reservation form to reserve
            // that slot.
            } else {
                echo '<td 
                      onClick="location.href=\'' . CONFURI . MAINFILE .
                      '/reserve/' . $day->ymd() . '/' . $time . '/' . $room_col[$c] .
                      '\'" bgcolor="gray"></td>';
            }
        }
        
        echo '</tr>';

        $time = timeadd( $time, SCHEDSLOT );
    }

    echo '</table>';
    show_footer();
}

function show_rooms() {
    $r = room::allrooms();
    show_header();
    echo '<p>';
    foreach ($r as $room) {
        echo '<form method="POST" action="' . CONFURI . MAINFILE . '/post" onsubmit="';
        echo "return confirm('Are you sure?')";
        echo '">';
        echo '<input type="hidden" name="post" value="deleteroom" />';
        echo '<input type="hidden" name="ID" value="' . $room->ID() . '" />';
        echo '<input type="hidden" name="delete" value="Yes" />';
        echo '<input type="submit" value="x" />';
        echo " <a href='" . CONFURI . MAINFILE . "/editroom/" . $room->ID() . "'>" . $room->name() . "</a> : " . $room->description() . "</form><br />";
    }
    echo '</p>';
    echo '<p><a href="' . CONFURI . MAINFILE . '/newroom">Add a new room</a></p>';
    show_footer();
}

/**
 * Display a form for a room. If the action is 'new', it will be a blank
 * form. If the action is 'edit', it will be filled in with the details
 * from the supplied room object.
 */
function room_form( $action = 'new', $room = false ) {

    if ( $action == 'edit' ) {
        $what = 'updateroom';
        $submit = 'Update room details';
    } else {
        $what = 'addroom';
        $submit = 'Add new room';
    }

    $name = ''; $description = ''; $ID = '';
    if ($room) {
	$name = 'value="' . $room->name() . '"';
        $description = $room->description();
        $ID = '<input type="hidden" name="ID" value="' . $room->ID() . '">';
    }

    ?>
    <form method="POST"
        action="<?php echo CONFURI . MAINFILE; ?>/post">
    <input type="hidden" name="post" value="<?php echo $what; ?>" />
    <?php echo $ID; ?>
    Name: <input name="name" <?php echo $name; ?>><br />
    Description: <textarea name="description"><?php echo $description; ?></textarea><br />
    <input type="submit" value="<?php echo $submit ?>">
    </form>
    <?php
}

function add_room() {
    unset( $_POST['ID'] );
    $room = new room( $_POST );
    $room->save();
    return $room->ID();
}

function update_room() {
    $ID = intval($_POST['ID']);
    $room = new room ( array ( 'ID' => $ID ) );
    $room->name($_POST['name']);
    $room->description($_POST['description']);
    $room->save();
    return $room->ID();
}

function delete_room($ID = 0) {
    if ( (0 != $ID) && ('Yes' == $_POST['delete']) ) {
        $room = new room( array ( 'ID' => $ID ) );
        $room->delete();
    }
}

function reservation_form( $event = 0 ) {
    if ( $event ) {
        $ds          = $event->ds();
        $time        = $event->starttime();
        $roomID      = $event->roomID();
        $end         = $event->endtime();
        $description = $event->description();
        $name        = $event->name();
        $action      = 'updatereservation';
    } else {
        $args   = explode( '/', $_SERVER['PATH_INFO'] );
        $ds     = $args[2];
        $time   = $args[3];
        $roomID = $args[4];
        $action = 'addreservation';
    }

    foreach ( room::allrooms() as $room ) {
        $rooms[$room->ID()] = $room->name();
    }

    ?>
    <form action='<?php echo CONFURI . MAINFILE . '/post'?>' method="POST">
    <input type="hidden" name="post" value="<?=$action?>">
    <?php
    if ( $event ) {
        echo '<input type="hidden" name="ID" value="' . $event->ID() .
            '">';
    }
    ?>
    Room: <select name="roomID"><?php
        echo selectlist( $rooms, $roomID ); ?></select><br />
    Event: <input name="name" value="<?=$name?>"><br />
    Description: <textarea name="description"><?=$description?></textarea><br />
    Date: <input name='ds' value="<?=$ds?>">(Nifty javascript popup calendar goes
    here)<br />
    Start: <input name="starttime" value="<?=$time?>">(Something nifty here to only
    permit start/end times that are legit)<br />
    End: <input name="endtime" value="<?=$end?>"><br />
    <input type="submit" value="Reserve room">
    </form>
    <?php
}

function post() {
// this is our generic POST handler, through which all data will be added 
// to the system.  Rather than clutter up the main switch() statement, we'll 
// clutter up a switch statement here.  
// At least we know were to look to add new actions, right?

// do we have anything being posted?
if (! isset($_POST['post'])) return false;

$destination = '/rooms'; // where to go when we're done?  Override in the switch

switch ($_POST['post']) {
    case 'addroom' :
        $ID = add_room();
    break;

    case 'updateroom' :
        update_room();
    break;

    case 'deleteroom' :
        $ID = intval($_POST['ID']);
        delete_room($ID);
    break;

    case 'addreservation' :
        add_reservation();
        $destination = '/';
    break;

    case 'updatereservation' :
        update_reservation();
        $destination = '/';
    break;

    case 'deletereservation' :
        delete_reservation();
    break;

    default : // safety catch-all
        $destination = '';
    break;
}

redirect_to(CONFURI . MAINFILE . "$destination");
}

function add_reservation() {
    $event = new event( $_POST );
    $event->save();
}

function event_details() {
    $args = explode ( '/', $_SERVER['PATH_INFO'] );
    // 0 is null, 1 is 'event', and 2 is the roomID
    $event = new event( array ( 'ID' => $args[2] ) );
    echo '<a href="' . CONFURI . MAINFILE . '/editreservation/' . $event->ID()
        . '">Edit</a>';
    echo '<pre>';
    print_r( $event );
    echo '</pre>';
}

/**
 * Description
 *
 * @param
 * @return
 */

function update_reservation() {
    $event = new event( array( 'ID' => $_POST['ID'] ) );
    $event->update( $_POST );
    $event->save();
    return;
}

// vim: filetype=php
?>
